import { moneyFormattedToNum, moneyFormat } from 'src/utils/index';
// 非空校验
export const checkEmptyString = (rule, value, callback) => {
  const label =
    Object.prototype.toString.call(rule.getLabel) === '[object Function]'
      ? rule.getLabel()
      : rule.label;
  const emptyErrMsg = `${label}不能为空`;
  if (!value) {
    callback(emptyErrMsg);
    return;
  }
  let valueStr = null;
  if (Object.prototype.toString.call(value) === '[object Object]') {
    valueStr = (value.value || '').trim();
  } else if (Object.prototype.toString.call(value) === '[object String]') {
    valueStr = value.trim();
  } else {
    callback();
    return;
  }
  if (!valueStr) {
    callback(emptyErrMsg);
    return;
  }
  callback();
};

// 名称校验
export const checkName = (maxLen = 50) => {
  return (rule, value, callback) => {
    const label =
      Object.prototype.toString.call(rule.getLabel) === '[object Function]'
        ? rule.getLabel()
        : rule.label;
    const emptyErrMsg = `${label}不能为空`;
    if (!value) {
      callback(emptyErrMsg);
      return;
    }
    let valueStr = null;
    const pattern = RegExp(/[#&\?%]/g); // 匹配是否含有#&?%等特殊字符
    if (Object.prototype.toString.call(value) === '[object Object]') {
      valueStr = (value.value || '').trim();
    } else {
      valueStr = value.trim();
    }
    if (!valueStr) {
      callback(emptyErrMsg);
      return;
    }
    if (pattern.test(valueStr)) {
      callback(`当前输入存在特殊字符，请重新输入`);
      return;
    }
    if (valueStr.length > maxLen) {
      callback(`当前输入超过${maxLen}位，请重新输入`);
      return;
    }
    callback();
  };
};

// 金额校验
export const checkAmount = (maxAmount = 1000000000) => {
  return (rule, value, callback) => {
    const label =
      Object.prototype.toString.call(rule.getLabel) === '[object Function]'
        ? rule.getLabel()
        : rule.label;
    const emptyErrMsg = `${label}不能为空`;
    if (!value) {
      callback(emptyErrMsg);
      return;
    }
    if (!/^\d*(,*\d*).?\d*$/g.test(value)) {
      callback('当前金额格式错误，请重新输入');
      return;
    }
    if (value && moneyFormattedToNum(value) > maxAmount) {
      callback(`请输入≤${moneyFormat(maxAmount)}的${label}`);
      return;
    }
    if (Number(value) === 0) {
      callback(`${rule.label}不能为0`);
      return;
    }
    callback();
  };
};
